package com.chenwc.common.fileUtils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;

/**
 * @author chenwc
 * @date 2024/4/1 22:23
 */
public class ReadFile {

    private static final Logger log = LoggerFactory.getLogger(ReadFile.class);


    /**
     * 以UTF-8字符编码读取文本文件内容（字符流）
     *
     * @param path 文件路径
     * @return 文件内容
     */
    public static String readFileByInputStreamReader(String path) {
        return readFileByInputStreamReader(path, StandardCharsets.UTF_8);
    }

    /**
     * 以指定字符编码读取文本文件内容（字符流）
     *
     * @param path    文件路径
     * @param charset 读取文件使用的字符编码
     * @return 文件内容
     */
    public static String readFileByInputStreamReader(String path, Charset charset) {
        File file = new File(path);
        log.info("读取文件路径: {}", file.getAbsolutePath());
        InputStreamReader inputStreamReader = null;
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            if (!file.exists()) {
                log.info("文件不存在，读取文件失败！");
                return null;
            }
            long start = System.currentTimeMillis();
            log.info("开始读取文件............");
            inputStreamReader = new InputStreamReader(Files.newInputStream(file.toPath()), charset);
            br = new BufferedReader(inputStreamReader);
            String string;
            //按行读取文件
            while ((string = br.readLine()) != null) {
                sb.append(string).append("\r\n");
            }
            long end = System.currentTimeMillis();
            log.info("读取文件成功............");
            log.info("读取文件耗时: {} ms", end - start);
        } catch (Exception e) {
            // TODO: handle exception
            log.error("Error occurred: ", e);
        } finally {
            try {
                if (null != br) {
                    br.close();
                }
                if (null != inputStreamReader) {
                    inputStreamReader.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
                log.error("Error occurred: ", e2);
            }
        }
        return sb.toString();
    }


    /**
     * 通过 FileInputStream 读取文件内容（字节流），最大读取文件大小为 Integer.MAX_VALUE (B)
     *
     * @param fis        FileInputStream
     * @param fileLength 文件大小
     * @return 二进制文件内容
     */
    public static byte[] readFileByInputStream(FileInputStream fis, long fileLength) {
        byte[] result = new byte[(int) fileLength];
        try {
            long start = System.currentTimeMillis();
            log.info("开始读取文件............");
            int available = fis.available();
            log.info("available: {}", available);
            if (available <= 0) {
                log.info("待读取文件为空文件，读取文件失败");
                return null;
            }
            byte[] buffer = new byte[1024 * 10];
            int bytesRead;
            int startIndex = 0;
            while ((bytesRead = readNBytes(fis, buffer, 0, buffer.length)) > 0) {
                //src 源数组，srcPos 从源数组哪个位置开始拷贝，dest 目标数组，destPos 从目标数组哪个位置开始复制，length 复制多少长度
                System.arraycopy(buffer, 0, result, startIndex, bytesRead);
                startIndex += bytesRead;
            }
            long end = System.currentTimeMillis();
            log.info("读取文件成功............");
            log.info("读取文件耗时: {} ms", end - start);
        } catch (Exception e) {
            log.error("Error occurred: ", e);
        } finally {
            // 在finally语句块当中确保流一定关闭。
            try {
                if (null != fis) {
                    fis.close();
                }
            } catch (Exception e2) {
                // TODO: handle exception
                log.error("Error occurred: ", e2);
            }
        }
        return result;
    }

    /**
     * 读取 InputStream 流中的数据
     *
     * @param inputStream InputStream 流
     * @param b           待读取的二进制数组
     * @param off         读取的起始位置
     * @param len         读取的长度
     * @return 读取到的字节数
     * @throws IOException IO异常
     */
    public static int readNBytes(InputStream inputStream, byte[] b, int off, int len) throws IOException {
        int n;
        int count;
        for (n = 0; n < len; n += count) {
            count = inputStream.read(b, off + n, len - n);
            if (count < 0) {
                break;
            }
        }

        return n;
    }

    /**
     * 通过 FileInputStream 读取文件内容（字节流），最大读取文件大小为 Integer.MAX_VALUE (B)
     *
     * @param path 文件路径
     * @return 二进制文件内容
     */
    public static byte[] readFileByFileInputStream(String path) {
        File file = new File(path);
        log.info("读取文件路径: {}", file.getAbsolutePath());
        byte[] result = null;
        try {
            if (!file.exists()) {
                log.info("文件不存在，读取文件失败！");
                return null;
            }
            result = readFileByInputStream(new FileInputStream(file), file.length());
        } catch (Exception e) {
            log.error("Error occurred: ", e);
        }
        return result;
    }
}